﻿namespace MsTestUtilities.SolutionAnalysis
{
    public interface IBuildConfiguration
    {
        IProject Project { get; }

        string Name { get; }

        bool TreatWarningsAsErrors { get; }

        string OutputPath { get; }
    }

    public class BuildConfiguration : IBuildConfiguration
    {
        public const string BuildConfigurationAttribute = " '$(Configuration)|$(Platform)' == ";

        private BuildConfiguration()
        {
        }

        public static BuildConfiguration FromPropertyGroup(IProject project, PropertyGroup propertyGroup)
        {
            return new BuildConfiguration
            {
                Project = project,
                Name = propertyGroup.GetAttributeValue("Condition")
                    .Replace(BuildConfigurationAttribute, string.Empty)
                    .Replace("'", string.Empty)
                    .Trim(),
                TreatWarningsAsErrors = propertyGroup.GetBoolFromElement("TreatWarningsAsErrors"),
                DebugSymbols = propertyGroup.GetBoolFromElement("DebugSymbols"),
                Optimize = propertyGroup.GetBoolFromElement("Optimize"),
                OutputPath = propertyGroup.GetElementValue("OutputPath"),
                WarningLevel = int.Parse(propertyGroup.GetElementValue("WarningLevel"))
            };
        }

        public static bool IsBuildConfiguration(PropertyGroup propertyGroup)
        {
            var conditionAttribute = propertyGroup.GetAttributeValue("Condition");
            if (conditionAttribute == null)
            {
                return false;
            }

            return conditionAttribute.StartsWith(BuildConfigurationAttribute);
        }

        public IProject Project { get; private set; }

        public string Name { get; private set; }

        public string Configuration
        {
            get { return Name.Substring(0, Name.IndexOf('|')); }
        }

        public string Platform
        {
            get { return Name.Substring(Name.IndexOf('|') + 1); }
        }

        public bool TreatWarningsAsErrors { get; private set; }

        public bool DebugSymbols { get; private set; }

        public bool Optimize { get; private set; }

        public string OutputPath { get; private set; }

        public int WarningLevel { get; private set; }

        public override string ToString()
        {
            return Name;
        }
    }
}
